<!--
 * @Date: 2022-11-10 14:27:08
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc: 
 * @LastEditTime: 2023-07-12 14:34:53
 * @FilePath: \opcConnector\pages\index.html
-->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Opc connector by chun2222</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="./layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>

<body>
    <ul class="layui-nav">
        <li class="layui-nav-item">
            <a href="/pages/">主界面 </a>
        </li>
        <li class="layui-nav-item">
            <a href="./doc.html" target="_blank">接口文档<span class="layui-badge-dot"></span></a>
        </li>
        <!--
        <li class="layui-nav-item">
          <a href=""><img src="//t.cn/RCzsdCq" class="layui-nav-img">我</a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;">修改信息</a></dd>
            <dd><a href="javascript:;">安全管理</a></dd>
            <dd><a href="javascript:;">退了</a></dd>
          </dl>
        </li> -->
    </ul>


    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>服务配置</legend>
    </fieldset>

    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">请选择服务器</label>
            <div class="layui-input-block">
                <select name="OpcServer" lay-filter="OpcServer" id="serverlist">
                </select>
            </div>
        </div>
        
       
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-primary layui-border-blue" lay-submit lay-filter="*">修改服务器</button>
            </div>
        </div>




        <div class="layui-form-item mt10">
            <label class="layui-form-label">当前服务器</label></label>
            <div class="layui-input-block" id="activeOpcServer">
                <input type="text" readonly class="layui-input">

            </div>
        </div>


        <button class="layui-btn  layui-btn-normal layui-btn-fluid mt10" id="loadtags">加载当前服务器点位</button>

    </div>



    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>点位浏览</legend>
        </legend>
    </fieldset>

    <div class="layui-row  layui-col-space10">
        <div class="layui-col-md6">
            <div class="tagbox">

                <div id="opctags" class="tree-box"></div>
            </div>
        </div>
        <div class="layui-col-md6 listtag">
            <p>点位：<span id="tagName"></span></p>
            <p>值：<span id="tagValue"></span></p>
            <p>质量：<span id="tagQuality"></span></p>
            <p>时间：<span id="tagTimestamp"></span></p>
            <p>
            <div class="layui-input-inline" style="width: 200px;"> <input id="setValue" type="text"
                    class="layui-input"></input> </div>
            <button class="layui-btn layui-btn-primary layui-border-blue" id="writeTag">修改值</button></p>

            <p> <button class="layui-btn  layui-btn-primary layui-btn-fluid layui-border-blue mt10"
                    id="reloadTag">刷新读取</button> </p>

        </div>
    </div>

 


    <script src="./layui/layui.js" charset="utf-8"></script>
    <script src="./jquery-3.5.1.min.js" charset="utf-8"></script>
    <!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
    <script>

        let Secret = "init"
        let activeOpcServer = ""
        const request = (url, data, callback, async = true) => {
            $.ajax({
                type: "POST",
                headers: {
                    Accept: "application/json; charset=utf-8",
                    Secret: Secret  //这个是自定义的请求头
                },
                async: async,
                url: url,
                contentType: "application/json",
                data: JSON.stringify(data),
                dataType: 'json',
                success: callback
            });
        }

        request("/init", "", function (re) {
            if (re.code == 0) {
                let data = re.data
                Secret = data.Secret
                activeOpcServer = data.OpcServer
                $("#activeOpcServer input").val(activeOpcServer)
            }else{
                layer.alert(res.msg, { icon: 2 });
            }

        }, false)




        layui.use(['tree', 'layer', 'form'], function () {
            var layer = layui.layer;
            var form = layui.form;

            form.on('submit', function (data) {
                let field = data.field;
                //设置服务器
                request("/SetServer", { Name: field.OpcServer }, function (res) {
                    if (res.code == 0) {
                        layer.msg("设置成功,需要手动重启服务");
                    } else {
                        layer.msg(res.msg);
                    }
                });

            });

            //初始化列表

            request("/ServerList", {}, (res) => {
                if (res.code == 0) {
                    const data = res.data
                    const html = data.map((item) => {
                        return `<option value="${item}">${item}</option>`
                    }).join("")
                    $("#serverlist").html(html)
                    form.render('select'); //刷新select选择框渲染
                } else {
                    layer.alert(res.msg, { icon: 2 });
                }
            })


            $("#loadtags").click(function () {
                layer.load(2);
                request("/GetChildren", {path:[]}, function (result) {
                    layer.closeAll('loading'); 
                    if (result.code == 0) {
                        let data = result.data;
                        $("#opctags").html("")
                         data.forEach(item => {
                            //url 编码
                            let data = [item.Name] 
                            $("#opctags").append(itemDom(item,0,  [item.Name] ))   
                         });
                    } else {
                        layer.alert(result.msg, { icon: 2 });
                    } 

                })
            })  

            //委托的方式
            $("#opctags").on("click", ".tag-item", function () {
                let name = $(this).data("name");
                let type = $(this).data("type");
                let tag = $(this).data("tag");
                let level = $(this).data("level"); 
                let status = $(this).data("status");
                let dir = JSON.parse(decodeURIComponent($(this).data("dir"))) ;
                 
                let that = $(this);

                //判断是不是点位
                if(type =="2"){
                    //点位 
                    $("#tagName").html(tag)
                    read(tag)
                    return 
                }


             
               request("/GetChildren", {path:dir}, function (result) {
                    layer.closeAll('loading'); 
                    if (status == "open") {
                        //关闭
                        that.data("status", "close")
                        that.find(".icon-add-reduce").html(`<img src="./images/add.svg">`)
                         //先移除
                         if($(`div[data-id='${encodeURIComponent(JSON.stringify(dir))}'`)){
                            $(`div[data-id='${encodeURIComponent(JSON.stringify(dir))}'`).remove()
                          }
                       
                        return
                    }

                    that.data("status", "open")
                     that.find(".icon-add-reduce").html(`<img src="./images/reduce.svg">`)
                    if (result.code == 0) {
                        let data = result.data;
                         let html = ""
                         if (data && data.length > 0) {
                            data.forEach(item => {
                            html += itemDom(item,level+1,dir.concat([item.Name]))   
                          }); 
                        //   //先移除
                        //   if($(`div[data-id='${encodeURIComponent(JSON.stringify(dir))}'`)){
                        //     $(`div[data-id='${encodeURIComponent(JSON.stringify(dir))}'`).remove()
                        //   }
                          that.after(`<div data-id="${encodeURIComponent(JSON.stringify(dir))}">${html}</div>`) 

                         }
                        
                    } else {
                        layer.alert(result.msg, { icon: 2 });
                    } 

                })
            })
              

        

            function itemDom(item,level,dir) {
               let dirStr =  encodeURIComponent(JSON.stringify(dir))
               let dirParentStr =  encodeURIComponent(JSON.stringify(dir.slice(0,dir.length-1)))
               let svg = ""
                if (item.Type == "1") {
                     svg = `<div class="icon-add-reduce"><img src="./images/add.svg"></div>`
                }
                return `<div data-parent="${dirParentStr}"  data-dir="${dirStr}"  data-level="${level}" data-name="${item.Name}"   data-type="${item.Type}"  data-tag="${item.Tag}" data-status="close"  class="tag-item tag-type${item.Type}" style="padding-left:calc(20 * ${level}px)"> <div><img src="./images/${item.Type}.svg"> ${item.Name}</div>${svg} </div>` 
            }

            $("#reloadTag").click(function () {
                let tagname = $("#tagName").text();
                read(tagname);
            })

            $("#writeTag").click(function () {
                let postObj = {}
                let tagname = $("#tagName").text();
                let value = $("#setValue").val();
                postObj[tagname] = value
                request("/Write", postObj, function (res) {
                    if (res.code == 0) {
                        layer.msg("写入成功"); 
                    } else {
                        layer.alert(res.msg, { icon: 2 });
                    }
                });
            })

            //读取点位
            const read = (tagname) => {
                request("/Read", { tags: [tagname] }, function (res) {
                    if (res.code == 0) {
                        let data = res.data[tagname];
                        $("#tagValue").text(data.Value);
                        $("#tagQuality").text(data.Quality);
                        $("#tagTimestamp").text(data.Timestamp);
                    } else {
                        layer.alert(res.msg, { icon: 2 });
                    }
                });
            }




        });
    </script>

</body>
<style> 
 body {
    overflow-x: hidden;
}

.listtag p {
    padding: 5px;
}

.mt10 {
    margin-top: 10px;
}

.tagbox {
    height: 500px;
    overflow: auto;
    padding:0 20px;
}
    .tag-item { display: flex;  gap: 10px; align-items: center; cursor: pointer; padding: 0 10px; }
</style>
</html>